package com.myFwk.util;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.myFwk.Entry.DemoEntry;
import com.myFwk.service.ExcelService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;

/**
 * @Title:
 * @Description:
 * @Author: guowl
 * @version： 1.0
 * @Date:2021/10/22
 * @Copyright: Copyright(c)2021 RedaFlight.com All Rights Reserved
 */
public class ExcelDataListener<T> extends AnalysisEventListener<T> {
    private Logger logger = LoggerFactory.getLogger(ExcelDataListener.class);
    /**
     * 每隔5条存储数据库，实际使用中可以3000条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 3000;

    /**
     * 缓存数据 将查出的数据首先存在缓存当中，这个首先要保证内存的
     *
     * @param fileName
     */
    private List<T> list = new ArrayList<>(BATCH_COUNT);
    private ExcelService service;

    public ExcelDataListener(ExcelService service) {
        this.service = service;
    }

    public ExcelDataListener() {
        this.list = list;
    }


    @Override
    public void invoke(T t, AnalysisContext analysisContext) {
        logger.info("解析到一条数据:{}",JSON.toJSONString(t,true));
        list.add(t);
        //当达到BATCH_COUT的时候，需要去存储一次数据库，防止数据过多造成OOM
        if (!CollectionUtil.isEmpty(list) && list.size() >=BATCH_COUNT) {
            service.save(list);
            list=new ArrayList<>(BATCH_COUNT);
        }
    }

    private void excelSave(List<T> list) {
        logger.info("{}条数据,开始存储数据库！", list.size());
        service.save(list);
        logger.info("数据保存成功！");
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // TODO 保存数据库操作
        excelSave( list);
        logger.info("所有数据保存成功！");
    }
}
